package com.sms.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.SocketException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 用户超时过滤器
 * @author 2011-12-30 下午10:20:11 by hzx
 */
public class TimeOutFilter implements Filter {

	/**
	 * 初始化
	 */
	public void init(FilterConfig config) throws ServletException {
	}

	/**
	 * 过滤
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		 HttpSession session = ((HttpServletRequest) request).getSession();
	        if (session != null && request.getParameter("operator")!= null &&
	        		!request.getParameter("operator").toString().trim().equals("login") &&
	        		session.getAttribute("userInfo") == null) {
	            session.invalidate();
	         // 设置响应内容格式
				response.setContentType("text/html;charset=utf-8");
				// 获取流
				PrintWriter out = response.getWriter();
				// 将数据以json格式打到客户端
				out.print("用户超时，请重新登录!");
				// 清空缓存
				out.flush();
				// 关闭流
				out.close();
	            request.getRequestDispatcher("index").forward(request,response);
	        } else{
	        	try{
	        		chain.doFilter(request, response);
	        	}catch(SocketException se){
	        		
	        	}
	        }
	}

	/**
	 * 销毁
	 */
	public void destroy() {
	}
}
